package com.huanxing.cloud.mall.api.listener;

import cn.hutool.core.util.ObjectUtil;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huanxing.cloud.common.core.constant.RocketMqConstants;
import com.huanxing.cloud.common.core.constant.SecurityConstants;
import com.huanxing.cloud.common.core.entity.Result;
import com.huanxing.cloud.common.myabtis.tenant.HxTenantContextHolder;
import com.huanxing.cloud.mall.api.service.IOrderRefundService;
import com.huanxing.cloud.mall.common.dto.OrderConsumerDTO;
import com.huanxing.cloud.mall.common.entity.OrderRefund;
import com.huanxing.cloud.mall.common.feign.FeignAliPayRefundService;
import com.huanxing.cloud.pay.common.dto.AliPayRefundRequestDTO;
import com.huanxing.cloud.security.handler.HxBusinessException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * 支付宝退款消费者 特别注意，这里topic必须和生产者的一致
 *
 * @author lijx
 * @date 2022/10/18
 */
@Slf4j
@Component
@AllArgsConstructor
@RocketMQMessageListener(topic = RocketMqConstants.ORDER_ALIPAY_REFUND_CANCEL_TOPIC,
		consumerGroup = RocketMqConstants.ORDER_ALIPAY_REFUND_CANCEL_TOPIC)
public class AliPayOrderRefundConsumer implements RocketMQListener<OrderConsumerDTO> {

	private final FeignAliPayRefundService feignAliPayRefundService;

	private final IOrderRefundService orderRefundService;

	@Override
	public void onMessage(OrderConsumerDTO orderConsumerDTO) {
		log.info("支付宝退款开始消费消息，消费信息:{}", orderConsumerDTO);
		HxTenantContextHolder.setCurrentTenantId(orderConsumerDTO.getTenantId());
		// 查询退款单
		OrderRefund orderRefund = orderRefundService.getOne(Wrappers.<OrderRefund>lambdaQuery()
			.eq(OrderRefund::getRefundTradeNo, orderConsumerDTO.getRefundTradeNo()));
		if (ObjectUtil.isNull(orderRefund)) {
			throw new HxBusinessException("无效订单号");
		}
		AliPayRefundRequestDTO queryRefundRequestDTO = new AliPayRefundRequestDTO();
		queryRefundRequestDTO.setOutRequestNo(orderConsumerDTO.getRefundTradeNo());
		queryRefundRequestDTO.setOutTradeNo(orderConsumerDTO.getOrderNo());
		Result<AlipayTradeFastpayRefundQueryResponse> alipayTradeQueryRefundResponseResult = feignAliPayRefundService
			.queryRefund(queryRefundRequestDTO, SecurityConstants.SOURCE_IN);
		if (!alipayTradeQueryRefundResponseResult.isOk()) {
			throw new HxBusinessException(alipayTradeQueryRefundResponseResult.getMsg());
		}
		AlipayTradeFastpayRefundQueryResponse alipayTradeFastpayRefundQueryResponse = alipayTradeQueryRefundResponseResult
			.getData();
		if (!"REFUND_SUCCESS".equals(alipayTradeFastpayRefundQueryResponse.getRefundStatus())) {
			throw new HxBusinessException("订单未支付成功");
		}
		orderRefund.setUserReceivedAccount("原路返还");
		orderRefundService.notifyRefund(orderRefund);
	}

}
